//
//  ViewController.m
//  LoginDemo
//
//  Created by XFB on 2017/6/12.
//  Copyright © 2017年 ZC. All rights reserved.
//

#import "ViewController.h"
#import "SuccessViewController.h"
#import "SearchHistoryCell.h"

@interface ViewController () <UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource, SearchHistoryCellDelegate>

@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) UITextField *accountTextField;
@property (nonatomic, strong) UITextField *passwordTextField;

@property (nonatomic, strong) UITableView *accountTableView; //搜索记录tableView
@property (nonatomic, strong) UIButton *loadMoreButton; //查看更多按钮
@property (nonatomic, strong) UIButton *loginButton; //登录按钮

// 搜索历史记录数组 NSMutableArray
@property (nonatomic, strong) NSMutableArray *searchData;
// 搜索历史缓存保存记录路径
@property (nonatomic, copy) NSString *searchHistoriesCachePath;
// 搜索历史记录缓存数量，默认为5条
@property (nonatomic, assign) NSUInteger searchHistoriesCount;

@end

@implementation ViewController

#pragma mark --- <View Life Cycle>

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupBasicSet];

    [self setupUI];
}

#pragma mark --- <Private Method>

- (void)setupBasicSet
{
    [self.accountTableView registerNib:[UINib nibWithNibName:NSStringFromClass([SearchHistoryCell class]) bundle:nil] forCellReuseIdentifier:@"cell"];
    self.searchHistoriesCachePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"Searchhistories.plist"];
    self.searchHistoriesCount = 5;
}

- (void)setupUI
{
    self.bgView = [[UIView alloc] initWithFrame:CGRectMake(15, 100, ScreenWidth-30, 44 * 2)];
    self.bgView.backgroundColor = UIColorFromRGB(0xdddddd);
    self.bgView.layer.masksToBounds = YES;
    [self.view addSubview:self.bgView];
    
    UIImageView *accountImgView = [[UIImageView alloc] init];
    accountImgView.frame = CGRectMake(5, 0, 44, 44);
    accountImgView.contentMode = UIViewContentModeCenter;
//    accountImgView.backgroundColor = [UIColor lightGrayColor];
    accountImgView.image = [UIImage imageNamed:@"public_icon_phone"];
    [self.bgView addSubview:accountImgView];
    
    self.accountTextField = [[UITextField alloc] init];
    self.accountTextField.tag = 10000;
    self.accountTextField.frame = CGRectMake(55, 0, ScreenWidth-125, 44);
    self.accountTextField.delegate = self;
    self.accountTextField.tintColor = RGB(54, 192, 120);
//    self.accountTextField.backgroundColor = [UIColor redColor];
    self.accountTextField.textColor = RGB(169, 169, 169);
    self.accountTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.accountTextField.leftViewMode = UITextFieldViewModeAlways;
    self.accountTextField.keyboardType = UIKeyboardTypePhonePad;
    self.accountTextField.placeholder = @"手机号码";
    self.accountTextField.font =  [UIFont fontWithName:@"PingFang SC" size:16];
    [self.accountTextField setValue:UIColorFromRGB(0X999999) forKeyPath:@"_placeholderLabel.textColor"];
    [self.bgView addSubview:self.accountTextField];

 
    self.loadMoreButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.loadMoreButton.frame = CGRectMake(CGRectGetMaxX(self.accountTextField.frame), 0, 40, 44);
    self.loadMoreButton.backgroundColor = [UIColor orangeColor];
    [self.loadMoreButton setImage:[UIImage imageNamed:@"login_dropdown"] forState:UIControlStateNormal];
    [self.loadMoreButton addTarget:self action:@selector(lookMoreButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.bgView addSubview:self.loadMoreButton];
    
    
    UIImageView *passwordImgView = [[UIImageView alloc] init];
    passwordImgView.frame = CGRectMake(5, 44, 44, 44);
    passwordImgView.contentMode = UIViewContentModeCenter;
    passwordImgView.image = [UIImage imageNamed:@"public_icon_password"];
    [self.bgView addSubview:passwordImgView];
    
    self.passwordTextField = [[UITextField alloc] init];
    self.passwordTextField.tag = 10001;
    self.passwordTextField.frame = CGRectMake(55, CGRectGetMaxY(self.accountTextField.frame), ScreenWidth-85, 44);
    self.passwordTextField.delegate = self;
    self.passwordTextField.tintColor = RGB(54, 192, 120);
    self.passwordTextField.textColor = RGB(169, 169, 169);
    self.passwordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.passwordTextField.leftViewMode = UITextFieldViewModeAlways;
    self.passwordTextField.keyboardType = UIKeyboardTypePhonePad;
    self.passwordTextField.placeholder = @"密码";
    self.passwordTextField.font =  [UIFont fontWithName:@"PingFang SC" size:16];
    [self.passwordTextField setValue:UIColorFromRGB(0X999999) forKeyPath:@"_placeholderLabel.textColor"];
    [self.bgView addSubview:self.passwordTextField];

    self.loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.loginButton.frame = CGRectMake(15, CGRectGetMaxY(self.bgView.frame) + 30, ScreenWidth-30, 40);
    self.loginButton.backgroundColor = UIColorFromRGB(0xEEEEEE);
    [self.loginButton setTitle:@"登录" forState:UIControlStateNormal];
    [self.loginButton setTitleColor:UIColorFromRGB(0x123733) forState:UIControlStateNormal];
    self.loginButton.titleLabel.font =  [UIFont fontWithName:@"PingFang SC" size:16];
    [self.loginButton addTarget:self action:@selector(loginButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.loginButton];

    
    [self.view addSubview:self.accountTableView];
    self.accountTableView.hidden = YES;
}


- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField.tag == 10000) {
        
        if (self.searchData.count) {
            self.accountTableView.hidden = NO;
            self.loadMoreButton.selected = YES;
        } else {
            self.accountTableView.hidden = YES;
            self.loadMoreButton.selected = NO;
        }
    } else {
        self.accountTableView.hidden = YES;
        self.loadMoreButton.selected = NO;
    }
}


#pragma mark --- <Events Response>

/// 登录按钮点击
- (void)loginButtonClick
{
    // 登录成功后，先移除再刷新
    [self.searchData removeObject:self.accountTextField.text];
    [self.searchData insertObject:self.accountTextField.text atIndex:0];
    [NSKeyedArchiver archiveRootObject:self.searchData toFile:self.searchHistoriesCachePath];
    if (self.searchData.count > self.searchHistoriesCount) {
        [self.searchData removeLastObject]; //如果搜索记录大于5条的时候，删除最后一条数据
    }
    
    [self.accountTableView reloadData];
    SuccessViewController *vc = [[SuccessViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

/// 查看更多按钮点击
- (void)lookMoreButtonClick:(UIButton *)button
{
    button.selected = !button.selected;

    if (button.selected) {
        
        if (self.searchData.count > 0) {
            self.accountTableView.hidden = NO;
        } else {
            self.accountTableView.hidden = YES;
            [self.accountTextField becomeFirstResponder];
        }
    } else {
        self.accountTableView.hidden = YES;
        [self.accountTextField resignFirstResponder];
    }
}

#pragma mark --- <Lazy Loading>

- (UITableView *)accountTableView
{
    if (_accountTableView == nil) {
        _accountTableView = [[UITableView alloc] initWithFrame:CGRectMake(55, 144, ScreenWidth-110, 135) style:UITableViewStylePlain];
        _accountTableView.backgroundColor = UIColorFromRGB(0xEEEEEE);
        _accountTableView.showsHorizontalScrollIndicator = NO;
        _accountTableView.showsVerticalScrollIndicator = NO;
        _accountTableView.delegate = self;
        _accountTableView.dataSource = self;
        _accountTableView.rowHeight = 45;
    }
    return _accountTableView;
}


#pragma mark --- <UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"%ld", self.searchData.count);
    return self.searchData.count;
}


#pragma mark --- <UITableViewDelegate>

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SearchHistoryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
//    cell.textLabel.text = self.searchData[indexPath.row];
    cell.searchRecordLabel.text = self.searchData[indexPath.row];
    cell.delegate = self;
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    SearchHistoryCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    self.accountTextField.text = cell.searchRecordLabel.text;
    
    [self.accountTextField resignFirstResponder];
    [self.passwordTextField becomeFirstResponder];
    
    self.accountTableView.hidden = YES;
    [self.accountTableView reloadData];
}

#pragma mark --- <SearchHistoryCellDelegate>
/// 点击搜索记录cell右侧删除按钮
- (void)clickSearchDeleteButton:(UIButton *)sender;
{
    // 获取当前cell
    SearchHistoryCell *cell = (SearchHistoryCell *)sender.superview.superview;
    // 移除搜索信息
    [self.searchData removeObject:cell.searchRecordLabel.text];
    
    if (self.searchData.count == 0) {
        self.accountTableView.hidden = YES;
    } else {
        self.accountTableView.hidden= NO;
        // 保存搜索信息
        [NSKeyedArchiver archiveRootObject:self.searchData toFile:self.searchHistoriesCachePath];
    }
    // 刷新tableView
    [self.accountTableView reloadData];
    
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
    self.accountTableView.hidden = YES;
}



- (NSMutableArray *)searchData
{
    if (_searchData == nil) {
        _searchData = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithFile:self.searchHistoriesCachePath]];
    }
    return _searchData;
}




@end
